import React from 'react';
import { Chart, Geom, Tooltip, Legend, Label} from 'bizcharts';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card,Select} from 'antd';
import numeral from 'numeral';
import DataSet from '@antv/data-set';
import styles from './Analysis.less';
const { Option } = Select;
// 测试html需要引入依赖文件
// <!-- 引入高德地图JSAPI -->
// <script src="//webapi.amap.com/maps?v=1.3&key=89a0871d1c4bf418cd9ab88c01e3bd5d"><\/script>
// <!-- 引入UI组件库（1.0版本） -->
// <script src="//webapi.amap.com/ui/1.0/main.js"><\/script>

// CDN START

const { AMapUI } = window;

const constructGeoJSON = (features) => {
  if (!features) return false;
  if (Array.isArray(features)) {
    return {
      type: 'FeatureCollection',
      features: [...features],
    };
  }
  return features;
};

// 传入adcode获取geojson，部分数据需要处理一下

const getGeojsonByCode = (adcode = 100000, withSub = true) => {
  if (!AMapUI) {
    return Promise.reject();
  }
  // 文档：https://lbs.amap.com/api/javascript-api/reference-amap-ui/geo/district-explorer
  return new Promise((resolve, reject) => {
    AMapUI.load('ui/geo/DistrictExplorer', (DistrictExplorer) => {

      const districtExplorer = new DistrictExplorer();
      districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
        if (error) {
          reject();
        }
        let res = null;
        if (withSub) {
          if(!areaNode) return false;
          res = areaNode.getSubFeatures();
        } else {
          res = areaNode.getParentFeature();
        }
        resolve(constructGeoJSON(res));
      });
    });
  });
};

// 绘制思路
// 前提：页面加载高德地图及其UI的SDK，参考html页面
// 1、通过高德的数据接口获取geojson数据
// 2、通过Dataset进行数据处理
// 3、绘制class

const rankingListData = [];
rankingListData.push(
	{ title: '北京',total: 500 },
	{ title: '上海',total: 400 },
	{ title: '河南',total: 350 },
	{ title: '山东',total: 200 },
	{ title: '安徽',total: 180},
	{ title: '河北',total: 120 },
	{ title: '湖南',total: 110 },
	{ title: '山西',total: 100 },
);

class AreaMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chinaGeo: null,
    };
  }

  componentDidMount() {
    getGeojsonByCode(100000, true).then((res) => {
      this.setState({ chinaGeo: res });
    });
  }

  processGeoData = (geoData, dataValue) => {
    const { features } = geoData;
    features.forEach((one) => {
      const name = one && one.properties && one.properties.name;
      dataValue.forEach((item) => {
        if (name.includes(item.name)) {
          one.value = item.value;
          one.key = item.key;
          one.regnum = item.regnum;
          one.noregnum = item.noregnum;
        }
      });
    });

    const geoDv = new DataSet.View().source(geoData, { type: 'GeoJSON' });
    return geoDv;
  };

  render() {

    const area = [
      { key: '10105', name: '广东', value: 30,regnum: 30,noregnum: 20},
      { key: '10125', name: '四川', value: 50,regnum: 50,noregnum: 40},
      { key: '10102', name: '安徽', value: 180,regnum: 180,noregnum: 160},
      { key: '10130', name: '浙江', value: 100,regnum: 100,noregnum: 80},
      { key: '10112', name: '湖北', value: 60,regnum: 60,noregnum: 40},
      { key: '10124', name: '上海', value: 400,regnum: 400,noregnum: 100},
      { key: '10103', name: '福建', value: 66,regnum: 66,noregnum: 30},
      { key: '10131', name: '重庆', value: 58,regnum: 58,noregnum: 30},
      { key: '10115', name: '江苏', value: 65,regnum: 65,noregnum: 35},
      { key: '10123', name: '陕西', value: 57,regnum: 57,noregnum: 27},
      { key: '10121', name: '山东', value: 200,regnum: 200,noregnum: 80},
      { key: '10109', name: '河北', value: 120,regnum: 120,noregnum: 60},
      { key: '10116', name: '江西', value: 96,regnum: 96,noregnum: 40},
      { key: '10113', name: '湖南', value: 110,regnum: 110,noregnum: 30},
      { key: '10129', name: '云南', value: 63,regnum: 63,noregnum: 20},
      { key: '10101', name: '北京', value: 500,regnum: 500,noregnum: 200},
      { key: '10104', name: '甘肃', value: 51,regnum: 51,noregnum: 20},
      { key: '10114', name: '吉林', value: 55,regnum: 55,noregnum: 25},
      { key: '10107', name: '贵州', value: 52,regnum: 52,noregnum: 20},
      { key: '10106', name: '广西', value: 46,regnum: 46,noregnum: 18},
      { key: '10110', name: '河南', value: 350,regnum: 350,noregnum: 100},
      { key: '10117', name: '辽宁', value: 82,regnum: 82,noregnum: 28},
      { key: '10118', name: '内蒙古', value: 61,regnum: 61,noregnum: 22},
      { key: '10128', name: '新疆', value: 50,regnum: 50,noregnum: 21},
      { key: '10111', name: '黑龙江', value: 48,regnum: 48,noregnum: 18},
      { key: '10126', name: '天津', value: 90,regnum: 90,noregnum: 26},
      { key: '10122', name: '山西', value: 100,regnum: 100,noregnum: 30},
      { key: '10108', name: '海南', value: 77,regnum: 77,noregnum: 33},
      { key: '10119', name: '宁夏', value: 44,regnum: 44,noregnum: 20},
      { key: '10120', name: '青海', value: 49,regnum: 49,noregnum: 16},
      { key: '10127', name: '西藏', value: 40,regnum: 40,noregnum: 20},
      { key: '10131', name: '台湾', value: 30,regnum: 30,noregnum: 15},
      { key: '10132', name: '澳门', value: 13,regnum: 20,noregnum: 8},
      { key: '10133', name: '香港', value: 15,regnum: 30,noregnum: 10},
    ];
    const { chinaGeo } = this.state;
    if (!chinaGeo) {
      return false;
    }
    const data = this.processGeoData(chinaGeo, area);
    const scale = {
      latitude: {
        sync: true,
        nice: false,
      },
      longitude: {
        sync: true,
        nice: false,
      },
      value: {
        formatter: val => numeral(val || 0).format('0.0%'),
      },
    };
    return [
      <Card
        bordered={false}
        title={
          <FormattedMessage
            id="app.statisticanalysis.staffByArea"
            defaultMessage="The Proportion of Sales"
          />
        }
        style={{ marginTop: 24 }}
        extra={
          <div className={styles.salesCardExtra}>
            {dropdownGroup}
            <div>
                <Select
                showSearch
                style={{minWidth: '120px'}}
                defaultValue="police_zjj"
                placeholder="请选择"
                onChange={this.handleSearchStaff}
                filterOption={(input, option) =>
                  option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                >
      				      <Option value="police_zjj">总警监</Option>
      				      <Option value="police_fzjj">副总警监</Option>
      				      <Option value="police_one_jj">一级警监</Option>
      				      <Option value="police_two_jj">二级警监</Option>
                    <Option value="police_tree_jj">三级警监</Option>
                    <Option value="police_one_jd">一级警督</Option>
                    <Option value="police_two_jd">二级警督</Option>
                    <Option value="police_three_jd">三级警督</Option>
                    <Option value="police_one_js">一级警司</Option>
                    <Option value="police_two_js">二级警司</Option>
                    <Option value="police_three_js">三级警司</Option>
                    <Option value="police_one_jy">一级警员</Option>
                    <Option value="police_two_jy">一级警员</Option>
      			    </Select>
            </div>
          </div>
        }
      >
      <div key="1" style={{ position: 'relative' }}>
         <Row>
             <Col xl={18} lg={12} md={12} sm={24} xs={24}>
                  <Chart height={500} width={645} scale={scale} data={data} padding={[0, 0, 0, 90]}>
                    <Tooltip />
                    <Geom
                      type="polygon"
                      position="longitude*latitude"
                      style={{ lineWidth: 1, stroke: '#505050' }}
                      // color={['value', ['#31c5f8', '#61d3f8', '#89dcfd', '#b0e8f8', '#d8f3ff']]}
                      color={['value', ['#d9f4ff', '#33c5f6']]}
                      tooltip={[
                        'name*value*regnum*noregnum',
                        (name,value,regnum,noregnum) => ({
                          name: name + `<div style="margin-left: 15px"><div>在编: ${regnum}人</div><div>未在编: ${noregnum}人</div></div>`,
                        }),
                      ]}
                    >
                    <Label
                        content={["name", (name)=>{
                          name = name.substr(0,2);
                          return name;
                        }]}
                        textStyle={{
                          textAlign: 'middle', // 文本对齐方向，可取值为： start middle end
                          fill: '#404040', // 文本的颜色
                          fontSize: '12', // 文本大小
                        }}
                        offsetY={10}
                        offsetX={-5}
                        autoRotate= {false} // 是否需要自动旋转，默认为 true
                      />
                      <Tooltip
                      showTitle={false}
                      triggerOn="click"
                      />
                      {/*<Legend
                        position="bottom-left"
                        offsetY={-130}
                        offsetX={-60}
                        slidable={false}
                        width={320}
                      />*/}
                    </Geom>
                  </Chart>
              </Col>
              <Col xl={6} lg={12} md={12} sm={24} xs={24}>
                  <div className={styles.salesRank}>
                    <h4 className={styles.rankingTitle}>
                      <FormattedMessage
                        id="app.statisticanalysis.staffAreaByRank"
                        defaultMessage="Sales Ranking"
                      />
                    </h4>
                    <ul className={styles.rankingList}>
                      {rankingListData.map((item, i) => (
                        <li key={item.title}>
                          <span
                            className={`${styles.rankingItemNumber} ${i < 3 ? styles.active : ''}`}
                          >
                            {i + 1}
                          </span>
                          <span className={styles.rankingItemTitle} title={item.title}>
                            {item.title}
                          </span>
                          <span className={styles.rankingItemValue}>
                            {numeral(item.total).format('0,0')}人
                          </span>
                        </li>
                      ))}
                    </ul>
                  </div>
              </Col>
         </Row>
      </div>
      </Card>
    ];
  }
}

export default AreaMap
